package cn.edu.fzu.homemaking.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.annotation.PreDestroy;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import cn.edu.fzu.homemaking.http.HttpClientFactory;
import cn.edu.fzu.homemaking.io.DingDingMessage;
import org.springframework.stereotype.Component;

/**
 * 系统下线
 *
 * @author fangxin
 * @date 2022/11/16
 */
@Component
public class ShutDownHelper {

    @PreDestroy
    public void shutdown() {

        //关闭钉钉机器人
        DingDingRobot.shutdownAll();
        //关闭http链接池
        HttpClientFactory.close();
    }


    /**
     * 执行部署功能
     * 
     * @return 是否执行成功
     */
    public static String deploy(String commend) {

        Process proc = null;
        try {
            Runtime rt = Runtime.getRuntime();
            proc = rt.exec(commend);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {

            }
            int exitVal = proc.waitFor();
            if (exitVal == 0) {
                return null;
            } else {
                return String.valueOf(exitVal);
            }
        } catch (Exception e) {
            return e.getMessage();
        } finally {
            if (proc != null) {
                proc.destroy();
            }
        }
    }


    public static String execute(String userName, String password, String ip, String cmd) throws IOException {
        String result = "";
        boolean isAuthed = false;

        if (isNodeReachable(ip)) {
            Connection conn = new Connection(ip);
            conn.connect();
            isAuthed = conn.authenticateWithPassword(userName, password);
            if (isAuthed) {
                Session session = conn.openSession();//打开一个会话
                session.execCommand(cmd);
                InputStream is = new StreamGobbler(session.getStdout());
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
                session.close();
                conn.close();
            } else {
                throw new IOException("认证失败，请检查用户名和密码");
            }
        }

        return result;
    }


    public static boolean isNodeReachable(String hostname) {
        try {
            return 0 == Runtime.getRuntime().exec("ping -c 1 " + hostname).waitFor();
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
